package com.icongyou.enterprise.talent_analysis.mapper;

import com.icongyou.enterprise.talent_analysis.entity.HrTemplatePreference;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.*;

/**
 * HR模板偏好设置Mapper测试
 */
@SpringBootTest
@Transactional
public class HrTemplatePreferenceMapperTest {

    @Autowired
    private HrTemplatePreferenceMapper mapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    // 使用数据库中已存在的租户ID和用户ID
    private static final String TEST_TENANT_ID = "550e8400-e29b-41d4-a716-446655440003"; // 阿里巴巴集团
    private static final String TEST_HR_USER_1 = "880e8400-e29b-41d4-a716-446655440401"; // 张经理
    private static final String TEST_HR_USER_2 = "880e8400-e29b-41d4-a716-446655440402"; // 李主管
    private static final String TEST_TEMPLATE_ID = "130e8400-e29b-41d4-a716-446655441301"; // 互联网技术岗位模板
    
    @BeforeEach
    public void setUp() {
        // 清理测试数据（确保测试独立性）
        jdbcTemplate.update("DELETE FROM hr_template_preference WHERE hr_user_id IN (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            TEST_HR_USER_1, TEST_HR_USER_2, "880e8400-e29b-41d4-a716-446655440403",
            "660e8400-e29b-41d4-a716-446655440101", "660e8400-e29b-41d4-a716-446655440102", 
            "660e8400-e29b-41d4-a716-446655440103", "660e8400-e29b-41d4-a716-446655440104",
            "660e8400-e29b-41d4-a716-446655440105", "660e8400-e29b-41d4-a716-446655440106"
        );
    }

    @Test
    public void testInsertAndSelectByHrUserId() {
        String hrUserId = TEST_HR_USER_1;
        
        HrTemplatePreference preference = new HrTemplatePreference();
        preference.setId(UUID.randomUUID().toString());
        preference.setHrUserId(hrUserId);
        preference.setEnterpriseId(TEST_TENANT_ID);
        preference.setTemplateId(TEST_TEMPLATE_ID);
        preference.setLastUsedAt(LocalDateTime.now());
        preference.setCreatedAt(LocalDateTime.now());
        preference.setUpdatedAt(LocalDateTime.now());

        int result = mapper.insert(preference);
        assertEquals(1, result);

        HrTemplatePreference retrieved = mapper.selectByHrUserId(hrUserId);
        assertNotNull(retrieved);
        assertEquals(hrUserId, retrieved.getHrUserId());
        assertEquals(TEST_TENANT_ID, retrieved.getEnterpriseId());
        assertEquals(TEST_TEMPLATE_ID, retrieved.getTemplateId());
    }

    @Test
    public void testSelectByHrUserId_notFound() {
        HrTemplatePreference retrieved = mapper.selectByHrUserId("nonexistent-hr");
        assertNull(retrieved);
    }

    @Test
    public void testUpdateByHrUserId() {
        String hrUserId = TEST_HR_USER_2;
        
        HrTemplatePreference preference = new HrTemplatePreference();
        preference.setId(UUID.randomUUID().toString());
        preference.setHrUserId(hrUserId);
        preference.setEnterpriseId(TEST_TENANT_ID);
        preference.setTemplateId(TEST_TEMPLATE_ID);
        preference.setLastUsedAt(LocalDateTime.now().minusDays(1));
        preference.setCreatedAt(LocalDateTime.now().minusDays(1));
        preference.setUpdatedAt(LocalDateTime.now().minusDays(1));

        mapper.insert(preference);

        // 创建另一个测试模板（使用标准UUID格式）
        String newTemplateId = UUID.randomUUID().toString();
        jdbcTemplate.update(
            "INSERT INTO portrait_template (id, enterprise_id, template_name, description, dimensions, is_active, ai_suggested, created_time, updated_time) " +
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            newTemplateId, TEST_TENANT_ID, "新模板", "测试描述", "{}", 0, 0, LocalDateTime.now(), LocalDateTime.now()
        );
        
        // 更新偏好设置
        preference.setTemplateId(newTemplateId);
        preference.setLastUsedAt(LocalDateTime.now());
        preference.setUpdatedAt(LocalDateTime.now());

        int result = mapper.updateByHrUserId(preference);
        assertEquals(1, result);

        HrTemplatePreference updated = mapper.selectByHrUserId(hrUserId);
        assertNotNull(updated);
        assertEquals(newTemplateId, updated.getTemplateId());
    }

    @Test
    public void testUpdateByHrUserId_notExists() {
        HrTemplatePreference preference = new HrTemplatePreference();
        preference.setHrUserId("nonexistent-hr");
        preference.setTemplateId("template003");
        preference.setLastUsedAt(LocalDateTime.now());
        preference.setUpdatedAt(LocalDateTime.now());

        int result = mapper.updateByHrUserId(preference);
        assertEquals(0, result);
    }

    @Test
    public void testUpdateByHrUserId_switchToDefaultTemplate() {
        String hrUserId = "880e8400-e29b-41d4-a716-446655440403"; // 王总监
        
        HrTemplatePreference preference = new HrTemplatePreference();
        preference.setId(UUID.randomUUID().toString());
        preference.setHrUserId(hrUserId);
        preference.setEnterpriseId(TEST_TENANT_ID);
        preference.setTemplateId(TEST_TEMPLATE_ID);
        preference.setLastUsedAt(LocalDateTime.now());
        preference.setCreatedAt(LocalDateTime.now());
        preference.setUpdatedAt(LocalDateTime.now());

        mapper.insert(preference);

        // 切换回默认模板（设置为null）
        preference.setTemplateId(null);
        preference.setUpdatedAt(LocalDateTime.now());

        int result = mapper.updateByHrUserId(preference);
        assertEquals(1, result);

        HrTemplatePreference updated = mapper.selectByHrUserId(hrUserId);
        assertNotNull(updated);
        assertNull(updated.getTemplateId());
    }

    @Test
    public void testClearTemplateReference() {
        // 创建要清除的测试模板（使用标准UUID格式）
        String templateToClear = UUID.randomUUID().toString();
        jdbcTemplate.update(
            "INSERT INTO portrait_template (id, enterprise_id, template_name, description, dimensions, is_active, ai_suggested, created_time, updated_time) " +
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            templateToClear, TEST_TENANT_ID, "待清除模板", "测试描述", "{}", 0, 0, LocalDateTime.now(), LocalDateTime.now()
        );
        
        // 创建其他模板（使用标准UUID格式）
        String otherTemplate = UUID.randomUUID().toString();
        jdbcTemplate.update(
            "INSERT INTO portrait_template (id, enterprise_id, template_name, description, dimensions, is_active, ai_suggested, created_time, updated_time) " +
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
            otherTemplate, TEST_TENANT_ID, "其他模板", "测试描述", "{}", 0, 0, LocalDateTime.now(), LocalDateTime.now()
        );

        // 插入多个使用该模板的偏好设置（使用已存在的学生用户作为测试）
        String[] hrUserIds = new String[]{"660e8400-e29b-41d4-a716-446655440101", "660e8400-e29b-41d4-a716-446655440102", "660e8400-e29b-41d4-a716-446655440103"};
        for (int i = 0; i < 3; i++) {
            HrTemplatePreference preference = new HrTemplatePreference();
            preference.setId(UUID.randomUUID().toString());
            preference.setHrUserId(hrUserIds[i]);
            preference.setEnterpriseId(TEST_TENANT_ID);
            preference.setTemplateId(templateToClear);
            preference.setLastUsedAt(LocalDateTime.now());
            preference.setCreatedAt(LocalDateTime.now());
            preference.setUpdatedAt(LocalDateTime.now());
            mapper.insert(preference);
        }

        // 插入一个使用其他模板的偏好设置
        String otherHrUserId = "660e8400-e29b-41d4-a716-446655440104";
        
        HrTemplatePreference other = new HrTemplatePreference();
        other.setId(UUID.randomUUID().toString());
        other.setHrUserId(otherHrUserId);
        other.setEnterpriseId(TEST_TENANT_ID);
        other.setTemplateId(otherTemplate);
        other.setLastUsedAt(LocalDateTime.now());
        other.setCreatedAt(LocalDateTime.now());
        other.setUpdatedAt(LocalDateTime.now());
        mapper.insert(other);

        int result = mapper.clearTemplateReference(templateToClear);
        assertEquals(3, result);

        // 验证引用已被清除
        for (int i = 0; i < 3; i++) {
            HrTemplatePreference updated = mapper.selectByHrUserId(hrUserIds[i]);
            assertNotNull(updated);
            assertNull(updated.getTemplateId());
        }

        // 验证其他模板的引用不受影响
        HrTemplatePreference otherUpdated = mapper.selectByHrUserId(otherHrUserId);
        assertNotNull(otherUpdated);
        assertEquals(otherTemplate, otherUpdated.getTemplateId());
    }

    @Test
    public void testClearTemplateReference_noMatches() {
        int result = mapper.clearTemplateReference("nonexistent-template");
        assertEquals(0, result);
    }

    @Test
    public void testInsert_duplicateHrUserId() {
        String hrUserId = "660e8400-e29b-41d4-a716-446655440105";
        
        HrTemplatePreference preference1 = new HrTemplatePreference();
        preference1.setId(UUID.randomUUID().toString());
        preference1.setHrUserId(hrUserId);
        preference1.setEnterpriseId(TEST_TENANT_ID);
        preference1.setTemplateId(TEST_TEMPLATE_ID);
        preference1.setLastUsedAt(LocalDateTime.now());
        preference1.setCreatedAt(LocalDateTime.now());
        preference1.setUpdatedAt(LocalDateTime.now());

        mapper.insert(preference1);

        // 使用另一个已存在的企业租户和模板
        String tenant2 = "550e8400-e29b-41d4-a716-446655440004"; // 腾讯科技
        String template2 = TEST_TEMPLATE_ID; // 复用现有模板测试唯一约束
        
        // 尝试插入相同的hrUserId（应该失败或被数据库唯一约束阻止）
        HrTemplatePreference preference2 = new HrTemplatePreference();
        preference2.setId(UUID.randomUUID().toString());
        preference2.setHrUserId(hrUserId);
        preference2.setEnterpriseId(tenant2);
        preference2.setTemplateId(template2);
        preference2.setLastUsedAt(LocalDateTime.now());
        preference2.setCreatedAt(LocalDateTime.now());
        preference2.setUpdatedAt(LocalDateTime.now());

        // 如果有唯一约束，这里会抛出异常
        try {
            mapper.insert(preference2);
            // 如果没有唯一约束，应该使用update而不是insert
        } catch (Exception e) {
            // 预期的唯一约束冲突
            assertTrue(true);
        }
    }

    @Test
    public void testSelectByHrUserId_withNullTemplateId() {
        String hrUserId = "660e8400-e29b-41d4-a716-446655440106";
        
        HrTemplatePreference preference = new HrTemplatePreference();
        preference.setId(UUID.randomUUID().toString());
        preference.setHrUserId(hrUserId);
        preference.setEnterpriseId(TEST_TENANT_ID);
        preference.setTemplateId(null); // 使用默认模板
        preference.setLastUsedAt(LocalDateTime.now());
        preference.setCreatedAt(LocalDateTime.now());
        preference.setUpdatedAt(LocalDateTime.now());

        mapper.insert(preference);

        HrTemplatePreference retrieved = mapper.selectByHrUserId(hrUserId);
        assertNotNull(retrieved);
        assertEquals(hrUserId, retrieved.getHrUserId());
        assertNull(retrieved.getTemplateId());
    }
}
